import json

from django.http import JsonResponse, HttpResponse, StreamingHttpResponse

from room_management.models import Room
# from utils.BuildModel import build_model
from utils.build_model import build_model
from utils.CaseModel import case_model
from utils.generate_model import generate_model
from utils.law_model import law_chat
from utils.model_api import ModelAPI
from .case_utils.document_case import CaseDocument
from .models import BuildInfo
import mysql.connector
from .models import Message  # 确保从正确的位置导入模型
from django.conf import settings

BUILD_DATA = settings.BUILD_DATA
# redis_client = get_redis_connection("default")

llm = ModelAPI()


def submit_user_data(request):
    data = json.loads(request.body.decode('utf-8'))  # 确保使用正确的编码

    # data = json.loads(request.body)
    message = Message(
        user_id=data.get('user_id'),
        text=data.get('text', None),
        room_id=data.get('room_id', None),
        role='user',
        model=data.get('model'),
        id=data.get('id')
    )

    if message.text is None:
        return JsonResponse({'message': '内容为空'}, status=201)

    # 假设 Room 类中有相关方法
    Room.create_room(data.get('room_id'), data.get('text'), data.get('user_id'))

    # 插入用户消息
    Message.create_message(
        id=message.id, user_id=message.user_id, text=message.text,
        room_id=message.room_id, role=message.role, model=message.model
    )
    # return JsonResponse({'message': '数据已提交'})


def stream(request):
    data = json.loads(request.body.decode('utf-8'))  # 确保使用正确的编码

    refresh = data.get('refresh')
    if not refresh:
        submit_user_data(request)

    user_text = data.get('text')
    model_name = data.get('model')
    assistant_message_id = data.get('assistantMessageId')

    # 根据 model_name 分发请求
    if model_name == "inference":
        # 运行模型或其他逻辑处理
        # return HttpResponse(run_fuzi(model_suffix, user_text, assistant_message_id, []), content_type='text/event-stream')
        pass
    elif model_name == "common":
        return StreamingHttpResponse(llm.chat_stream(user_text), content_type="text/event-stream",
                                     headers={'Cache-Control': 'no-cache'})
        pass
    elif model_name == "caseModel":
        return StreamingHttpResponse(case_model(user_text), content_type="text/event-stream",
                                     headers={'Cache-Control': 'no-cache'})
        pass
    elif model_name == "buildModel":
        # return HttpResponse(build_model(user_text, assistant_message_id), content_type='text/event-stream')
        return StreamingHttpResponse(build_model(user_text), content_type="text/event-stream",
                                     headers={'Cache-Control': 'no-cache'})
        pass
    elif model_name == "lawModel":
        return StreamingHttpResponse(law_chat(user_text), content_type="text/event-stream",
                                     headers={'Cache-Control': 'no-cache'})
        pass
    elif model_name == "generate":
        return StreamingHttpResponse(generate_model(user_text), content_type="text/event-stream",
                                     headers={'Cache-Control': 'no-cache'})
        pass
    return JsonResponse({'message': '未处理的模型类型'})


def set_key_value(request):
    if request.method == "POST":
        data = json.loads(request.body)
        assistant_message_id = data.get('assistantMessageId')
        # 假设已配置Redis
        # redis_client.set(assistant_message_id, "end")
        # redis_client.expire(assistant_message_id, 600)
        return JsonResponse({'message': 'success'}, status=200)


def message_add(request):
    data = json.loads(request.body.decode('utf-8'))  # 确保使用正确的编码

    user_id = data.get('user_id')
    text = data.get('text')
    room_id = data.get('room_id')
    model = data.get('model')
    assistantMessageId = data.get('assistantMessageId')
    refresh = data.get('refresh')

    if refresh:
        Message.update_message(id=assistantMessageId, text=text, model=model)
    else:
        Message.create_message(id=assistantMessageId, user_id=user_id, text=text,
                               room_id=room_id, role='assistant', model=model)
    return JsonResponse({'message': "success"})


def chat(request):
    data = json.loads(request.body.decode('utf-8'))  # 确保使用正确的编码

    user_id = data.get('user_id')
    text = data.get('text')
    room_id = data.get('room_id')
    model = data.get('model')
    message_id = data.get('id')
    refresh = data.get('refresh')

    if not text:
        return JsonResponse({'message': '内容为空'}, status=201)

    isNew = Room.create_room(room_id, text, user_id)

    if not refresh:
        Message.create_message(id=message_id, user_id=user_id, text=text, room_id=room_id,
                               role='user', model=model)

    response = f"AI回答：{data.get('assistantMessageId')}"

    Message.create_message(id=data.get('assistantMessageId'), user_id=user_id, text=response,
                           room_id=room_id, role='assistant', model=model)

    return JsonResponse({'assistant': response, 'isNew': isNew})


def get_all_messages(request):
    data = json.loads(request.body.decode('utf-8'))  # 确保使用正确的编码

    room_id = data.get('room_id')
    messages = Message.get_messages_by_room(room_id)
    return JsonResponse({'data': [msg.serialize() for msg in messages]}, status=200)


def delete_message(request):
    data = json.loads(request.body.decode('utf-8'))  # 确保使用正确的编码

    Message.delete_message_by_room_id(data.get('room_id'))
    return JsonResponse({'message': 'success'}, status=200)


def get_build_by_id(request, build_id, page, size):
    page = max(1, int(page))
    size = max(1, int(size))
    offset = (page - 1) * size

    build = BuildInfo.get_build_by_id(build_id)
    if build is None:
        return JsonResponse({
            'message': 'build not found'
        })

    # 连接数据库
    connection = mysql.connector.connect(
        host=BUILD_DATA['host'],
        user=BUILD_DATA['user'],
        password=BUILD_DATA['password'],
        database=BUILD_DATA['database']
    )
    cursor = connection.cursor()

    # 获取总行数
    total_sql_str = f"SELECT COUNT(*) FROM ({build.sql_str}) AS count_table"
    cursor.execute(total_sql_str)
    total = cursor.fetchone()[0]

    # 执行分页查询
    paginated_sql_str = f"{build.sql_str} LIMIT {size} OFFSET {offset}"
    cursor.execute(paginated_sql_str)

    # 提取表头
    headers = [description[0] for description in cursor.description]
    # 数组字典，字段从1开始
    arr = []
    head_title = [index for index in range(len(headers))]

    for row in cursor.fetchall():
        arr.append(dict(zip(head_title, row)))

    # 关闭数据库连接
    cursor.close()
    connection.close()

    return JsonResponse({
        'headers': headers,
        'list': arr,
        'total': total
    })


def get_case_page(request):
    data = json.loads(request.body)
    search_data = data.get('search_data', "")
    page_number = data.get("page_number", 1)
    page_size = data.get("page_size", 10)

    DisputeFocus = data.get("DisputeFocus", None)
    CoreFacts = data.get("CoreFacts", None)
    Keywords = data.get("Keywords", None)
    flag = data.get("flag", None)

    if flag == 1:
        Keywords += "/" + "/".join(search_data)
        Keywords = Keywords.split("/")

        search_data = {
            "DisputeFocus": DisputeFocus,
            "CoreFacts": CoreFacts,
            "Keywords": Keywords
        }

    cases, total = CaseDocument.search_page(search_data, page_number, page_size, flag)

    return JsonResponse({
        "data": {
            "data": [case.serialize() for case in cases],
            "page_number": page_number,
            "page_size": page_size,
            "total": total
        }
    })


def get_case_by_id(request, case_id):
    case = CaseDocument.get_by_id(case_id)
    if case is None:
        return JsonResponse({"message": "Case not found"}, status=404)
    return JsonResponse(case.serialize())
